package com.example.image.demos.controller;


import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.image.demos.dto.ImageDto;
import com.example.image.demos.entity.Image;
import com.example.image.demos.entity.ImageAlbum;
import com.example.image.demos.entity.User;
import com.example.image.demos.mapper.IImageDao;
import com.example.image.demos.mapper.IImageAlbumDao;
import com.example.image.demos.mapper.IUserDao;
import com.example.image.demos.service.IAlbumService;
import com.example.image.demos.service.IImageService;
import com.example.image.demos.service.IImageAlbumService;
import com.example.image.demos.service.impl.AlbumServiceImpl;
import com.example.image.demos.service.impl.UserServiceImpl;
import com.example.image.demos.util.FileBean;
import com.example.image.demos.util.Result;
import com.example.image.demos.util.UserThread;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ts
 * @since 2024-11-18
 */
@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
public class UserController {
    private final FileBean fileBean;
    @Autowired
    private IUserDao iuserDao;
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("login")
    public Result login(@RequestParam(value = "uid") Integer uid,
                        @RequestParam(value = "password") String password, HttpSession session) {
        //数据库判断是否有这个人的信息
        User nowuesr = (User)session.getAttribute("user");
        //没有代表正在登录
        if (nowuesr != null&&nowuesr.getUser_id()==uid) {
            return Result.fail(400, "已经登录", null);
        }
        //判断是否存在数据库
        User user = new LambdaQueryChainWrapper<User>(iuserDao)
                .eq(User::getUser_id, uid)
                .eq(User::getPassword, password)
                .one();
        System.out.println("test");
        if (user == null) {
            return Result.fail(400, "登录失败", null);
        } else {
            session.setAttribute("user", user);
            return Result.ok(200, "登录成功", user.getRole_id());
        }
    }

    //文件上传功能
    @PostMapping("/uploadFile")
    public Result fileUpload(@RequestParam("file") MultipartFile file) throws JSONException {
        // 文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传文件名称为:{}, 后缀名为:{}", fileName, suffixName);
        File fileTempObj = new File(fileBean.getDir() + File.separator + fileName);
        System.out.println("fileBean = " + fileBean.getDir());
        // 检测目录是否存在
      /*  if (!fileTempObj.getParentFile().exists()) {
            fileTempObj.getParentFile().mkdirs();
        }*/
        // 使用文件名称检测文件是否已经存在
       /* if (fileTempObj.exists()) {
            return Result.fail(100,"失败","1");
        }*/
        try {
            // 写入文件:方式1
            file.transferTo(fileTempObj);
        } catch (Exception e) {
            log.error("发生错误: {}", e);
            return Result.fail(100, "失败", "1");
        }
        return Result.ok("文件上传成功");
    }

    //上传到oss
    @PostMapping("/uploadOSS")
    public Result uploadOSS(@RequestParam("file") MultipartFile file) throws JSONException, IOException {
        boolean result = userService.uploadOSS(file);
        if (result) {
            return Result.ok(200, "上传成功", null);
        }
        return Result.fail(400, "上传失败", null);
    }

    //文件上传qi
    @PutMapping("uploadQi")
    public Result uploadQi(@RequestParam("file") MultipartFile file, ImageDto imageDto) throws JSONException, IOException {
        //返回一个路径
        String url = userService.uploadQi(file, imageDto);
        //获取当前线程登录用户id
        Integer userId = UserThread.getUser().getUser_id();
        if (url != null) {
            Image image1 = new Image();
            image1.setImage_name(imageDto.getImageName());
            image1.setImage_detail(imageDto.getImageDetail());
            image1.setImage_format(file.getContentType());
            image1.setUpload_address(url);
            image1.setCreate_time(LocalDateTime.now());
            image1.setUser_id(userId);
            iImageDao.insert(image1);
            //存一个图片进数据库
            return Result.ok(200, "success", null);
        }
        return Result.fail(400, "上传失败", null);
    }

    //文件下载qi
    @Autowired
    private IImageDao iImageDao;

    @PostMapping("/download")
    public Result download(Integer image_id) {
        Image image = new LambdaQueryChainWrapper<>(iImageDao)
                .eq(Image::getImage_id, image_id)
                .one();
        String url = image.getUpload_address();
        System.out.println("url = " + url);
        if (url != null) {
            return Result.ok(200, "下载成功", url);
        }
        return Result.fail(400, "找不到文件", null);
    }

    //文件夹删除功能
    @Autowired
    private IImageService iImageService;
    @Autowired
    private IImageAlbumService iImageAlbumService;
    @Autowired
    private IAlbumService ialbumService;

    @GetMapping("/del")
    public Result delete(@RequestBody  List <Integer> albumids) {
        //把数据库中的图片移入到回收站

        for (Integer albumId : albumids) {
            UpdateWrapper<ImageAlbum> wrapper = new UpdateWrapper<>();
            wrapper.eq("album_id", albumId)
                    .set("album_id", 1);
            boolean b = iImageAlbumService.update(wrapper);
            if (!b) {
                return Result.fail(400,"操作失败",null);
            }
        }
        //删除文件在数据库中的数据
        boolean del = ialbumService.removeByIds(albumids);
        if (del){
            return Result.ok(200, "success", null);
        }
        return Result.fail(400, "操作失败", null);
    }

}


